/**
 * 比较用户路由和所有路由的函数
 * 
 * 该函数用于将用户路由与所有路由进行比较，找出匹配的路由并返回
 * 主要用于权限验证或角色基础上的路由配置，确保用户只能访问他们有权访问的路由
 * 
 * @param {Array} userRouters - 用户被授权访问的路由数组
 * @param {Array} allRouters - 所有可用的路由数组
 * @returns {Array} 匹配的路由数组，即用户实际可以访问的路由
 */
export const compareRouters = (userRouters = [], allRouters = []) => {
  const matchedRouters = []
  // 遍历 userRouters 数组
  allRouters.forEach(allItem => {
    userRouters.forEach(userItem => {
      if (userItem.title === allItem.meta.title) {
        if (userItem.children && userItem.children.length > 0) {
          allItem.children = compareRouters(userItem.children, allItem.children)
        }
        matchedRouters.push(allItem)
      }
    })
  })

  return matchedRouters
}

/**
 * 检查path是否存在于目标路由数组
 */
export const isRouteExist = (path, routes) => {
  for (const route of routes) {
    if (route.path === path) {
      return true
    }
  }
  return false
}

/**
 * 检查用户是否有权限访问
 * @param {String} toPath 目标路径
 * @param {Array} routes 权限路由数组
 * @param {String} basePath 基础路径，用于处理嵌套路由
 * @returns 路径被包含返回true，否则返回false
 */
export const isPathIncluded = (toPath, routes, basePath = '') => {
  for (const route of routes) {
    let fullPath = basePath === '/' ? route.path : basePath + '/' + route.path
    if (toPath === fullPath) {
      return true // 找到了匹配的路径，有权访问
    }
    if (route.children && route.children.length > 0) {
      // 递归检查子路由
      if (isPathIncluded(toPath, route.children, fullPath)) {
        return true
      }
    }
  }
  return false
}
